<?php
define('IN_ADMIN',true);
new CSession_Mysql();
class CAdmin{
	public function __construct(){
		$this->check_admin();
		$this->check_priv();
		$this->check_hash();
	}
	
	/**
	 * 模板加载
	 */
	public static function admin_tpl($file, $m = ''){
		$m = empty($m) ? ROUTE_M : $m;
		if(empty($m)) return false;
		return RF_PATH.'views'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.$file.'.tpl.php';
	}
	
	/**
	 * 取得菜单导航
	 * Enter description here ...
	 * @param unknown_type $parentid
	 */
	final public static function admin_menu($parentid = ''){
		$parentid = intval($parentid);
		$menudb = new Menu_Model();
		$menu = $menudb->select(array('parentid' => $parentid,'display'=>1));
		if($_SESSION['roleid'] == 1) return $menu;
		$privdb = new Admin_role_priv_Model();
		$result = array();
		foreach ($menu as $value) {
			$r = $privdb->get_one(array('m'=>$value['m'],'c'=>$value['c'],'a'=>$value['a'],'roleid'=>$_SESSION['roleid']));
			if($r) $result[] = $value;
		}
		return $result;
	}
	
	/**
	 * 提示信息页面跳转
	 * showmessage('登录成功', array('默认跳转地址'=>'admin'));
	 * @param string $msg 提示信息
	 * @param mixed(string/array) $url_forward 跳转地址
	 * @param int $ms 跳转等待时间
	 */
	public static function showmessage($msg, $url_forward = 'goback', $ms = 1250){
		if(defined('IN_ADMIN')){
			include(self::admin_tpl('showmessage', 'admin'));
		}
		exit;
	}
	
	/**
	 * 检测用户是否登录
	 */
	final private function check_admin(){
	if(ROUTE_M =='admin' && ROUTE_C =='index' && ROUTE_A == 'login') {
			return true;
		} else {
			if(!isset($_SESSION['userid']) || !isset($_SESSION['roleid']) || !$_SESSION['userid'] || !$_SESSION['roleid']) self::showmessage('您还没登录，请登录！','?m=admin&c=index&a=login');
		}
	}
	
	/**
	 * 权限判断
	 */
	final public function check_priv(){
		if(ROUTE_M == 'admin' && ROUTE_C == 'index' && in_array(ROUTE_A, array('login','init','login_out'))) return true;
		if($_SESSION['roleid'] == 1) return true;
		if(preg_match('/^public/', ROUTE_A)) return true;
		$action = ROUTE_A;
		if(preg_match('/^ajx_/', ROUTE_A)) $action = substr(ROUTE_A, 4);
		$privdb = new Admin_role_priv_Model();
		$r = $privdb->get_one(array('m'=>ROUTE_M,'c'=>ROUTE_C,'a'=>$action,'roleid'=>$_SESSION['roleid']));
		if(!$r) self::showmessage('您没有权限操作该项!');
	}
	
	/**
	 * 预防跨站攻击
 	 * 检查hash值，验证用户数据安全性
 	 */
	final private function check_hash() {
		if(preg_match('/^public_/', ROUTE_A)|| ROUTE_M =='admin' && ROUTE_C =='index'||in_array(ROUTE_A, array('login','login_out'))) {
			return true;
		}
		if(isset($_GET['ron_hash']) && $_SESSION['ron_hash'] != '' && ($_SESSION['ron_hash'] == $_GET['ron_hash'])) {
			return true;
		} elseif(isset($_POST['ron_hash']) && $_SESSION['ron_hash'] != '' && ($_SESSION['ron_hash'] == $_POST['ron_hash'])) {
			return true;
		} else {
			self::showmessage('数据校验错误',HTTP_REFERER);
		}
	}
}